
package com.insigma.business.qrcode.soldier._bff.impl;


import cn.hutool.core.bean.BeanUtil;
import com.insigma.business.common.utils.PriInfoHandleUtil;
import com.insigma.business.qrcode.common.dto.CommonAdminAreaDTO;
import com.insigma.business.qrcode.common._consumer.CommonAdminAreaConsumer;
import com.insigma.business.qrcode.common.template.BasePagingResponse;
import com.insigma.business.qrcode.common.util.*;
import com.insigma.business.qrcode.common.vo.*;
import com.insigma.business.qrcode.soldier._bff.SoldierApplyInfoBffProvider;
import com.insigma.business.qrcode.soldier._consumer.*;
import com.insigma.business.qrcode.soldier.dto.*;
import com.insigma.business.qrcode.soldier.dto.gov.BaseProviderImpl;
import com.insigma.business.qrcode.common.template.area.ServiceCallback;
import com.insigma.business.qrcode.soldier.request.*;
import com.insigma.business.qrcode.common.template.area.ScenarioCodeEnum;
import io.micrometer.core.instrument.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.List;


@Slf4j
@Service
@Component("soldierApplyInfoBffProvider")
public class SoldierApplyInfoBffProviderImpl extends BaseProviderImpl implements SoldierApplyInfoBffProvider {

    @Autowired
    private SoldierApplyInfoConsumer soldierApplyInfoConsumer;

    @Autowired
    private CommonAdminAreaConsumer adminAreaConsumer;

    @Autowired
    private GovOrgConsumer govOrgConsumer;

    @Autowired
    private SoldierApplyCheckConsumer soldierApplyCheckConsumer;

    @Resource
    SoldierConsumer soldierConsumer;

    @Resource
    SoldierBasicInfoConsumer soldierBasicInfoConsumer;


    @Override
    public BaseResponse<String> saveSoldierApplyInfo(SoldierApplyInfoInsertRequest request) {

        BizCheckUtil.checkNotNull(request, "request的请求参数不能为空");
        BizCheckUtil.checkNotNull(request.getResidentAdminAreaCode(), "地区不能为空");
        BizCheckUtil.checkNotNull(request.getGender(), "性别不能为空");
        BizCheckUtil.checkNotBlank(request.getSoldierTypeDictCode(), "老兵类型不能为空");
        BizCheckUtil.checkMobile(request.getMobile());
        BizCheckUtil.checkIDCardNO(request.getIdCardNo());
        BaseResponse<String> soldierApplyInfoResponse = soldierApplyInfoConsumer.saveSoldierApplyInfo(request);

        return soldierApplyInfoResponse;
    }

    @Override
    public BaseResponse<String> checkSoldierApplyInfoBySoldierId(BaseApiRequest request) {
        return soldierApplyInfoConsumer.checkSoldierApplyInfoBySoldierId(request.getSoldierId());
    }

    @Override
    public BaseResponse<String> saveSoldierApplyInfoByFWZ(SoldierApplyInfoInsertRequest soldierApplyInfoInsertRequest) {
        SessionGovEmployee sessionGovEmployee = RpcContextUtil.getSessionGovEmployee();
        BizCheckUtil.checkNotNull(sessionGovEmployee, "用户非法");

        soldierApplyInfoInsertRequest.setCreatorId(sessionGovEmployee.getUserId());
        return soldierApplyInfoConsumer.saveSoldierApplyInfoByFWZ(soldierApplyInfoInsertRequest);
    }

    @Override
    public BaseResponse<SoldierApplyInfoDTO> getSoldierApplyInfoByIdCardNo(BaseApiRequest request) {
        BaseResponse<SoldierApplyInfoDTO> soldierApplyInfoByIdCardNo = soldierApplyInfoConsumer.getSoldierApplyInfoById(request.getId());
        return soldierApplyInfoByIdCardNo;
    }

    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> listWaitTasks(SoldierApplyInfoSearchRequest request) {
//        final SessionGovEmployee sessionGovEmployee = RpcContextUtil.getSessionGovEmployee();
//        CommonAdminAreaDTO area = adminAreaConsumer.findAdminAreaOfEmployee(sessionGovEmployee.getUserId());
//        request.setAdminCode(area.getId());
        BasePagingResponse<List<SoldierApplyInfoDTO>> listBasePagingResponse = soldierApplyInfoConsumer.listWaitTasks(request);
        List<SoldierApplyInfoDTO> dto = listBasePagingResponse.getDto();
        buildArea(dto);
        return listBasePagingResponse;
    }

    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> listDoneTasks(SoldierApplyInfoSearchRequest request) {
//        final SessionGovEmployee sessionGovEmployee = RpcContextUtil.getSessionGovEmployee();
//        CommonAdminAreaDTO area = adminAreaConsumer.findAdminAreaOfEmployee(sessionGovEmployee.getUserId());
//
//        request.setAdminCode(area.getId());
        BasePagingResponse<List<SoldierApplyInfoDTO>> result = soldierApplyInfoConsumer.listDoneTasks(request);
        List<SoldierApplyInfoDTO> dto = result.getDto();

        buildArea(dto);
        return result;
    }

    private void buildArea(List<SoldierApplyInfoDTO> dto) {
        if (!CollectionUtils.isEmpty(dto)) {
            for (SoldierApplyInfoDTO soldierApplyInfoDTO : dto) {
                CommonAdminAreaDTO adminAreaById = adminAreaConsumer.getAdminAreaById(soldierApplyInfoDTO.getResidentAdminAreaCode());
                if (adminAreaById != null) {
                    soldierApplyInfoDTO.setArea(adminAreaById.getFullValuePath());
                }
            }
        }
    }


    @Override
    public BaseResponse<Boolean> completeTask(SoldierApplyInfoInsertRequest request) {
//        final SessionGovEmployee sessionGovEmployee = RpcContextUtil.getSessionGovEmployee();
//        BizCheckUtil.checkNotNull(sessionGovEmployee, "用户非法");
//
//        request.setCreatorId(sessionGovEmployee.getUserId());
//        request.setCreatorName(sessionGovEmployee.getUsername());
        BaseResponse<Boolean> b = soldierApplyInfoConsumer.completeTask(request);
        return b;
    }


    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> searchSoldierApplyInfo(final SoldierApplyInfoSearchRequest searchRequest) {

        final BasePagingResponse<List<SoldierApplyInfoDTO>> basePagingResponse = new BasePagingResponse<>();
        serviceTemplate.execute(basePagingResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(searchRequest, "查询分页SoldierApplyInfo的请求参数不能为空");
            }

            @Override
            public void executeService() {


                BasePagingResponse<List<SoldierApplyInfoDTO>> listBasePagingResponse = soldierApplyInfoConsumer.searchSoldierApplyInfo(searchRequest);
                BeanUtil.copyProperties(listBasePagingResponse, basePagingResponse);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_APPLY_INFO_SEARCH;
            }
        });

        return basePagingResponse;
    }

    @Override
    public BaseResponse<ContactNoDTO> queryDistinctContactNo(SimpleApiRequest request) {
        if (request == null || request.getAdminAreaCode() == null) {
        SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
        if (sessionSoldier != null) {
            BaseResponse<SoldierApplyInfoDTO> applyInfo = soldierApplyInfoConsumer.getSoldierApplyInfoBySoldierId(sessionSoldier.getUserId());
            if (applyInfo.getDto() != null) {
                request.setAdminAreaCode(applyInfo.getDto().getResidentAdminAreaCode());
            }
        }

    }
        return soldierApplyInfoConsumer.queryDistinctContactNo(request);
    }


    @Override
    public BaseResponse<SoldierApplyInfoDTO> getSoldierApplyInfo(final BaseGetRequest baseGetRequest) {

        final BaseResponse<SoldierApplyInfoDTO> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(baseGetRequest, "获取单条SoldierApplyInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) baseGetRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                final BaseResponse<SoldierApplyInfoDTO> soldierApplyInfoResponse = soldierApplyInfoConsumer.getSoldierApplyInfo(baseGetRequest);
                BeanUtil.copyProperties(soldierApplyInfoResponse, baseResponse);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_APPLY_INFO_GET;
            }
        });
        return baseResponse;
    }



    public BaseResponse<Integer> updateSoldierApplyInfo(final SoldierApplyInfoUpdateRequest updateRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(updateRequest, "修改SoldierApplyInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getId(), "id不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierId(), "操作人不能为空");
                BizCheckUtil.checkNotBlank(updateRequest.getModifierType(), "操作人类型不能为空");
            }

            @Override
            public void executeService() {
                BaseResponse<Integer> soldierApplyInfoResponse = soldierApplyInfoConsumer.updateSoldierApplyInfo(updateRequest);
                BeanUtil.copyProperties(soldierApplyInfoResponse, baseResponse);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_APPLY_INFO_UPDATE;
            }
        });
        return baseResponse;
    }


    @Override
    public BaseResponse<Integer> deleteSoldierApplyInfo(final BaseDeleteRequest deleteRequest) {

        final BaseResponse<Integer> baseResponse = new BaseResponse<>();
        serviceTemplate.execute(transactionTemplate, baseResponse, new ServiceCallback() {
            @Override
            public void check() {
                BizCheckUtil.checkNotNull(deleteRequest, "逻辑删除SoldierApplyInfo的请求参数不能为空");
                BizCheckUtil.checkNotBlank((String) deleteRequest.getId(), "id不能为空");
            }

            @Override
            public void executeService() {
                deleteRequest.setModifierId("test");
                deleteRequest.setModifierType(UserTypeEnum.SERVANT.name());
                BaseResponse<Integer> soldierApplyInfoResponse = soldierApplyInfoConsumer.deleteSoldierApplyInfo(deleteRequest);
                BeanUtil.copyProperties(soldierApplyInfoResponse, baseResponse);
            }

            @Override
            public ScenarioCodeEnum getScenarioEnum() {
                return ScenarioCodeEnum.SOLDIER_APPLY_INFO_DELETE_LOGICALLY;
            }
        });
        return baseResponse;
    }

    @Override
    public BaseResponse<Integer> deleteUnsuccessfulApply(BaseDeleteRequest deleteRequest) {

        BizCheckUtil.checkNotNull(deleteRequest, "请求不能为空");
        BizCheckUtil.checkNotNull(deleteRequest.getId(), "id不能为空");

        SessionUtils.buildDeleteOfGov(deleteRequest);
        return soldierApplyInfoConsumer.deleteUnsuccessfulApply(deleteRequest);
    }

    @Override
    public BaseResponse<String> reApplySoldierQR(SoldierApplyInfoUpdateRequest request) {

        BizCheckUtil.checkNotNull(request, "request的请求参数不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode(), "地区不能为空");
        BizCheckUtil.checkNotBlank(request.getResidentAdminAreaCode().trim(), "地区不能为空");
        BizCheckUtil.checkNotNull(request.getGender(), "性别不能为空");
        BizCheckUtil.checkNotNull(request.getSoldierTypeDictCode(), "老兵类型不能为空");
        BizCheckUtil.checkMobile(request.getMobile());
        BizCheckUtil.checkIDCardNO(request.getIdCardNo());

        SessionSoldier sessionSoldier = RpcContextUtil.getSessionSoldier();
        BizCheckUtil.checkNotNull(sessionSoldier, "用户非法");
        request.setSoldierId(sessionSoldier.getUserId());
        return soldierApplyInfoConsumer.reApplySoldierQR(request);
    }

    @Override
    public BaseResponse<String> saveSoldierApplyInfoOfOuterTemporary(SoldierApplyInfoInsertRequest request) {

        request.setSoldierId(SessionUtils.getSoldierUserId());
        return soldierApplyInfoConsumer.saveSoldierApplyInfoOfOuterTemporary(request);
    }

    @Override
    public BaseResponse<Integer> getRemainingTimesOfOuterTemporary() {

        return soldierApplyInfoConsumer.getRemainingTimesOfOuterTemporary(SessionUtils.getSoldierUserId());
    }

    @Override
    public BaseResponse<String> saveSoldierApplyInfoOfOutsider(SoldierApplyInfoInsertRequest request) {

        request.setSoldierId(SessionUtils.getSoldierUserId());
        return soldierApplyInfoConsumer.saveSoldierApplyInfoOfOutsider(request);
    }

    @Override
    public BaseResponse<String> reApplySoldierQROfOutsider(SoldierApplyInfoUpdateRequest request) {

        request.setSoldierId(SessionUtils.getSoldierUserId());
        return soldierApplyInfoConsumer.reApplySoldierQROfOutsider(request);
    }

    @Override
    public BaseResponse<String> updateApplyInfoOfOutsider(SoldierApplyInfoUpdateRequest request) {

        SessionUtils.buildModifierOfGov(request);
        return soldierApplyInfoConsumer.updateApplyInfoOfOutsider(request);
    }


    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> getCzSoldierApplyInfo(SoldierApplyInfoSearchRequest searchRequest) {
        return soldierApplyInfoConsumer.searchCzApplyInfo(searchRequest);
    }

    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> getCheckApplyInfo(SoldierApplyInfoSearchRequest searchRequest) {
        String govUserId = SessionUtils.getGovUserId();
        BizCheckUtil.checkNotNull(govUserId, "govUserId不为空");
        searchRequest.setGovUserId(govUserId);
        return soldierApplyInfoConsumer.getCheckApplyInfo(searchRequest);
    }

    @Override
    public BasePagingResponse<List<SoldierApplyInfoDTO>> searchAllCheckApplyInfo(SoldierApplyInfoSearchRequest searchRequest) {
        String govUserId = SessionUtils.getGovUserId();
        if (StringUtils.isNotEmpty(govUserId)) {
            //根据当前登录用户获取其部门所在机构
            List<GovOrgDTO> dto = govOrgConsumer.listByEmployeeId(SessionUtils.getGovUserId()).getDto();
            if (dto != null && dto.size() > 0) {
                String adminAreaCode = dto.get(0).getLeafAdminAreaId();
                //&& String adminAreaCode = "330106000000";
                if (StringUtils.isNotEmpty(adminAreaCode)) {
//                    if (adminAreaCode.substring(0,6).equals("330100")){
//                        searchRequest.setResidentAdminAreaCode(adminAreaCode.substring(0,4));
//                    }else {
//                        searchRequest.setResidentAdminAreaCode(adminAreaCode.substring(0,6));
//                    }
                    //searchRequest.setApplyType("OUTSIDER");
                    log.info("获取当前登录人的AdminAreaCode====="+adminAreaCode);
                    searchRequest.setResidentAdminAreaCode(adminAreaCode);
                    searchRequest.setIsOnline("0");
                    return soldierApplyInfoConsumer.searchCzApplyInfo(searchRequest);
                }
            }
        }
        return null;
    }

    @Override
    public BaseResponse<List<SoldierApplyCheckDTO>> getCheckProcess(SoldierApplyCheckRequest soldierApplyCheckRequest) {
        BizCheckUtil.checkNotNull(soldierApplyCheckRequest.getApplyId(), "申请id不能为空");
        return soldierApplyCheckConsumer.getSoldierApplyCheckInfo(soldierApplyCheckRequest.getApplyId());
    }

    @Override
    public BaseResponse<SoldierBasicInfoDTO> getSoldierBasicInfoByCardAndNameAndCheck(BaseApiRequest request) {
        BizCheckUtil.checkNotBlank(request.getIdCardNo(), "证件号码不能为空");
        SoldierBasicInfoDTO soldierBasicInfoByCard = soldierBasicInfoConsumer.getSoldierBasicInfoByCard(request.getIdCardNo()).getDto();
        if (soldierBasicInfoByCard == null) {
            return ResponseUtil.buildSuccessResponse(null);
        }
//        if (!soldierBasicInfoByCard.getRealName().equals(dto.getOuterSysNickName())) {
//            log.error("身份采集姓名不符合：dto:{}，soldierBasicInfoByCard:{} ", dto, soldierBasicInfoByCard);
//        //    return ResponseUtil.buildFailResponse(ErrorCodeEnum.SSH_NAME_NOT_EQUAL);
//            return new BaseResponse<>();
//        }


        CommonAdminAreaDTO adminAreaById = adminAreaConsumer.getAdminAreaById(soldierBasicInfoByCard.getResidentAdminAreaCode());
        if (adminAreaById != null) {
            soldierBasicInfoByCard.setAdminAreaFullPath(adminAreaById.getFullValuePath());
        }
        return ResponseUtil.buildSuccessResponse(soldierBasicInfoByCard);
    }

    @Override
    public BaseResponse<Boolean> updateSoldierApplyInfoAssignCode(SoldierApplyInfoAssignCodeUpdateRequest request) {
        return soldierApplyInfoConsumer.updateSoldierApplyInfoAssignCode(request);
    }

    public BaseResponse<String> insertCheckProcess(SoldierApplyCheckInsertRequest soldierApplyCheckInsertRequest) {
        return soldierApplyCheckConsumer.insertSoldierApplyCheck(soldierApplyCheckInsertRequest);
    }

}
